/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.sprite.blit.canvas;
import flash.display.DisplayObjectContainer;
import flash.display.Shape;
import hapi.sprite.blit.BlitGraphicsSpriteSheetDisplay;
import hapi.sprite.blit.NMEBlitSpriteSheetDisplay;
import hapi.sprite.display.Displayable;
import hapi.sprite.sheet.NMETileSpriteSheet;
import haxe.FastList;

class NMEBlitCanvas extends BlitCanvasBase, implements Displayable {

	var displays:FastList<NMEBlitSpriteSheetDisplay>;
	var spriteSheet:NMETileSpriteSheet;
	var xyids:Array<Float>;
	public var shape(default, null):Shape;
	
	
	public function new(spriteSheet:NMETileSpriteSheet, width:Int, height:Int, ?frameRate:Null<Float>) {
		super(width, height, frameRate);
		this.spriteSheet = spriteSheet;
		this.xyids = new Array();
		this.displays = new FastList<NMEBlitSpriteSheetDisplay>();
		this.shape = new Shape();
	}
	
	public override function refresh():Void {
		var gfx = shape.graphics;
		gfx.clear();
		//var xyids:Array<Float> = new Array();
		//for ( d in displays ) d.addToRender(xyids);
		spriteSheet.drawTilesOn(gfx, xyids);
		super.refresh();
	}
	
	public function createDisplay(?x:Float=0.0, ?y:Float=0.0):NMEBlitSpriteSheetDisplay {
		var display = new NMEBlitSpriteSheetDisplay(spriteSheet, xyids, x, y);
		displays.add(display);
		return display;
	}
	
	public function removeDisplay(display:NMEBlitSpriteSheetDisplay) {
		if (displays.remove(display)) {
			xyids.pop(); xyids.pop();  xyids.pop(); //3 elements less
			reallocateDisplays();
		}
	}
	
	inline function reallocateDisplays() {
		var offset = 0;
		for ( d in displays ) {
			d.reallocate(offset);
			offset += 3;
		}
	}
	
	public function addToDisplayList(root:DisplayObjectContainer, ?x:Null<Float>, ?y:Null<Float>):Void {
		root.addChild(shape);
		if(x != null) shape.x = x;
		if(y != null) shape.y = y;
	}
}